package com.bw.lib_net.custom;

import com.bw.lib_net.entity.ResponseEntity;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/17 15:39
 * @Description :
 */
public class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;
    private Type type; //类型 自己加的

    public CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter, Type type) {
        this.gson = gson;
        this.adapter = adapter;
        this.type = type;
    }

    @Override public T convert(ResponseBody value) throws IOException {
        String string = value.string();//json串
        //1.按照ResponseEntity解析，不解析data字段，避免null
        ResponseEntity responseEntity = gson.fromJson(string, ResponseEntity.class);
        if (responseEntity != null && responseEntity.getCode() == -1){
            return (T)responseEntity;
        }
        //2.按照ResponseEntity<T>解析，全部解析
        return gson.fromJson(string, type);
    }
}
